import cv2
import socket
import threading
import sys
from collections import deque
def capture_video():
    global Running
    #创建camera对象,用来读取摄像头数据
    camera = cv2.VideoCapture(0)
    while Running:
        if camera.isOpened():
            success, frame = camera.read()
            if success:
                frame_que.append(frame)
                #print('sucessful cap')
    sys.exit()
def send_video():
    global Running
    #传输图像的大小
    resolution = (640,480)
    #可以指定压缩程度,值越大压缩率越大
    img_quality = 15
    #创建客户套接字,使用udp
    cs = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    while Running:
        try:
            frame = frame_que.popleft()
        except:
            frame = None
        if frame is not None:
            #print('got a frame from queue')
            frame = cv2.resize(frame, resolution)
            #编码
            _, frame_code = cv2.imencode('.jpg', frame, [int(cv2.IMWRITE_JPEG_QUALITY), img_quality])
            try:
                cs.sendto(frame_code,(serverIp, serverPort)) #发送视频帧数据
            except:
                print('发送失败')
                Running = False
                break
    try:
        cs.sendto('1'.encode(),(serverIp, serverPort)) #发送关闭消息
    except:
        print('连接已断开')
    cs.close()
serverIp = '10.35.36.91'
#目的服务器套接字的端口号
serverPort = 12000 
#摄像头开关
global Running
Running = False
#视频帧队列
frame_que = deque()
serverIp = input('输入目的主机ip：')
if __name__ == '__main__':
    capture_thread = threading.Thread(target = capture_video)
    send_thread = threading.Thread(target = send_video)
    while True:  
        start_send = input("输入1开始捕捉视频,0停止捕捉视频：")
        if start_send == '1':
            Running = True
            try:
                capture_thread.start()
                send_thread.start()
            except:
                break
        else:
            Running = False
            sys.exit()
            break